package com.fwtai.security;

import com.fwtai.config.ConfigFile;
import com.fwtai.tool.ToolClient;
import org.springframework.context.annotation.Bean;
import org.springframework.security.config.annotation.authentication.configuration.AuthenticationConfiguration;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityCustomizer;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.SecurityFilterChain;

@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class SecurityConfig{

  @Bean
  public WebSecurityCustomizer webSecurityCustomizer() {
    return (web) -> web.ignoring().antMatchers(ConfigFile.IGNORE_URLS);
  }

  @Bean
  public SecurityFilterChain filterChain(final HttpSecurity http,final AuthenticationConfiguration configuration) throws Exception {
    return http.authorizeRequests()
      .antMatchers(ConfigFile.URL_PROCESSING)
      .permitAll()
      .anyRequest()
      .authenticated()
      .and()
      .formLogin()
      .loginPage(ConfigFile.URL_LOGIN_PAGE)
      .permitAll()
      .and()
      .logout()
      .logoutUrl(ConfigFile.URL_LOGOUT)
      .permitAll()
      .logoutSuccessHandler((request,response,authentication)->{
        SecurityContextHolder.clearContext();
        ToolClient.responseJson(ToolClient.createJsonSuccess("退出注销成功"),response);
      })
      .permitAll()
      .and().cors()
      .and().csrf().disable()
      .addFilter(new LoginAuthentication(configuration.getAuthenticationManager()))//登录鉴权
      .addFilter(new AuthorizationFilter(configuration.getAuthenticationManager()))//权限拦截
      .sessionManagement()
      .sessionCreationPolicy(SessionCreationPolicy.STATELESS)
      .and()
      .exceptionHandling()
      .authenticationEntryPoint(new AuthFailureEntryPoint())
      .and()
      .build();
  }
}